<?php
namespace Admin\Controller;

use Think\Controller;
use Think\Page;

class AriticleController extends Controller {

	public function index() {
		$ArticleModel = M('article');
		$count = $ArticleModel->count();
		$page = new Page($count);
		
		$ariticles = $ArticleModel->where(array(
			'status' => 1,
		))->order('id DESC')->select();
		
		if($ariticles) {
			foreach($ariticles as $newKey => &$newVal) {
				$newVal ['time'] = date('Y-m-d H:i:s', $newVal ['created']);
				$newVal ['link'] = getBaseUrl().'/action/zixun.php?a=detail&id='.$newVal ['id'];
			}
		}
		
		$this->assign("pageList", $ariticles);
		$this->assign("page", $page->show());
		$this->display();
	}
	
	public function search() {
		//跳转到单图文列表
		$fenyePage = new FenyePage();
		$pageSize = 15;
		if(!empty($_GET['pageNow'])) {
			$pageNow = $_GET['pageNow'];
		} else {
			$pageNow = 1;
		}
		$fenyePage->pageSize = $pageSize;
		$fenyePage->pageNow = $pageNow;
		$adminZixunService = new AdminZixunService();
		$key = $_GET ['key'];
		
		if ($key) {
			//先取出为单图文的key，在根据key查询文章
			$adminZixunService->searchZixunByPageAndKey($fenyePage, $key);
			$smarty->assign('key', $key);
		} else {
			$adminZixunService->getAllByPage($fenyePage);
		}
		
		if($fenyePage->res_array) {
			foreach($fenyePage->res_array as $newKey => $newVal) {
				$fenyePage->res_array [$newKey] ['time'] = date('Y-m-d H:i:s', $newVal ['created']);
			}
		}
		
		$fenyePage->goUrl = site_url()."/AdminZixunControl.php?flag=list";
		$fenyePage->showPage($fenyePage);
		$smarty->assign("pageList",$fenyePage->res_array);
		$smarty->assign("page", $fenyePage->navigate);
		$smarty->assign("article_total", $fenyePage->rowCount);
		$smarty->assign("page_now", $pageNow);
		$smarty->display("../admin/zixun/list.html");
	}
	
	public function seaWxLink() {
		$this->assign("zixunLink", get_url().'/action/zixun.php?a=list');
		$this->display();
	}
	
	public function add() {
		if(!IS_POST) {
			//跳转到添加单图文页面
			$this->display();
		} else {
			//处理添加单图文的post请求
			if(isset($_POST['zixun_zhaiyao'])) {
				$zixun_zhaiyao = $_POST['zixun_zhaiyao'];
			} else {
				$zixun_zhaiyao = null;
			}
		
			$data = array(
				'type' => 'zixun',
				'title' => htmlspecialchars($_POST['zixun_title']),
				'img_path' => $_POST['zixun_img_path'],
				'zhaiyao' => htmlspecialchars($zixun_zhaiyao),
				'content' => htmlspecialchars($_POST['content']),
			);
			
			if(empty($adminZixunService)) {
				$adminZixunService = new AdminZixunService();
			}
		
			$addNewsId = $adminZixunService->create($data);
			if($addNewsId) {
				$smarty->assign("message", "添加资讯速递成功！");
			} else {
				$smarty->assign("message", "添加资讯速递失败！");
				$smarty->assign("err_file", "AdminZixunControl.php?flag=add");
				$smarty->assign("err_line", "51");
			}
			$links = array();
			$links[0] = array('href'=>SITE_URL."/control/AdminZixunControl.php?flag=list",'text'=>'返回资讯速递列表');
			$links[1] = array('href'=>SITE_URL."/control/AdminZixunControl.php?flag=add",'text'=>'继续添加资讯速递');
			$smarty->assign("links", $links);
			$smarty->display("message.html");
			exit();
		}
	}
	
	public function edit() {
		$id = $_GET['id'];
		if(!IS_POST) {
			//编辑单图文
			if(empty($adminZixunService)) {
				$adminZixunService = new AdminZixunService();
			}
			$item = $adminZixunService->getById($id);
			$item ['time'] = date('Y-m-d H:i:s', $item ['created']);
			$smarty->assign("item",$item);
				
			$smarty->assign('singal', $item ['type'] == 'singal');
			$image_path = $item['zixun_img_path'];
			$smarty->assign("image_path",substr($image_path, strrpos($image_path,"/")+1, strlen($image_path)));
			$smarty->display("../admin/zixun/edit.html");
			exit();
		} else {
			//处理添加单图文的post请求
			if(isset($_POST['zixun_zhaiyao'])) {
				$zixun_zhaiyao = $_POST['zixun_zhaiyao'];
			} else {
				$zixun_zhaiyao = null;
			}
			$id = $_POST['id'];
			$data = array(
					'title' => htmlspecialchars($_POST['zixun_title']),
					'img_path' => $_POST['zixun_img_path'],
					'zhaiyao' => htmlspecialchars($zixun_zhaiyao),
					'content' => htmlspecialchars($_POST['content']),
			);
			if(empty($adminZixunService)) {
				$adminZixunService = new AdminZixunService();
			}
			$updateFlag = $adminZixunService->updateOneZixun($data, $id);
			if($updateFlag) {
				//调用生成静态文件的函数
				$smarty->assign("message", "编辑成功！");
			} else {
				$smarty->assign("message", "编辑失败！");
				$smarty->assign("err_file", "AdminZixunControl.php?flag=edit&id=$id");
				$smarty->assign("err_line", "51");
			}
			$links = array();
			$links[0] = array('href'=>SITE_URL."/control/AdminZixunControl.php?flag=list",'text'=>'返回资讯列表');
			$smarty->assign("links", $links);
			$smarty->display("message.html");
			exit();
		}
	}
	
	public function delete() {
		$id = $_GET['id'];
		if(empty($adminZixunService)) {
			$adminZixunService = new AdminZixunService();
		}
		
		$result = $adminZixunService->delete($id);
		if($result) {
			//调用生成静态文件的函数
			$smarty->assign("message", "删除成功！");
		} else {
			$smarty->assign("message", "删除失败！");
			$smarty->assign("err_file", "AdminZixunControl.php?flag=list");
			$smarty->assign("err_line", "51");
		}
		
		$links = array();
		$links[0] = array('href'=>SITE_URL."/control/AdminZixunControl.php?flag=list",'text'=>'返回资讯速递列表');
		$smarty->assign("links", $links);
		$smarty->display("message.html");
		exit();
	}
	
	public function ajax_delete_news_image() {
		$news_key = $_GET['news_key'];
		$image_path = $_GET['image_path'];
		if(empty($adminNewsImageService)) {
			$adminNewsImageService = new AdminNewsImageService();
		}
		$deleteFlag = $adminNewsImageService->deleteOneNewsKeyByNewskey($news_key);
		if($deleteFlag) {
			//删除图片
			$news_image = substr($image_path, strrpos($image_path,"/")+1, strlen($image_path));
			$pic_path = dirname(dirname(__FILE__));
			$pic_path = $pic_path."/data/files/news/". $news_image;
			if(file_exists($pic_path)) {
				if(!empty($news_image)){
					unlink($pic_path);
				}
			}
			echo "1";
		} else {
			echo "0";
		}
		exit();
	}
	
	public function ajax_upload_img() {
		//ajax上传封面图片,先删除原来图片
		if(isset($_FILES['mypic'])) {
			$picname = $_FILES['mypic']['name'];
			$picsize = $_FILES['mypic']['size'];
			if ($picname != "") {
				if ($picsize > 1024000) {
					echo '图片大小不能超过1M';
					exit;
				}
				$type = strstr($picname, '.');
				if ($type != ".gif" && $type != ".jpg" && $type != ".png") {
					echo '图片格式不对！';
					exit;
				}
				$rand = rand(100, 999);
				$pics = date("YmdHis") . $rand ;
				//上传路径
				$pic_path = dirname(dirname(__FILE__));
				$pic_dir = $pic_path."/data/files/news";
				if(!is_dir($pic_dir)) {
					mkdir($pic_dir);
				}
				$pic_path = $pic_path."/data/files/news/". $pics. $type;
				move_uploaded_file($_FILES['mypic']['tmp_name'], $pic_path);
		
				resize($pic_path, 145, 95);
			}
			$size = round($picsize/1024,2);
			$arr = array(
					'name'=>$picname,
					'pic'=>$pics. $type,
					'size'=>$size
			);
			echo json_encode($arr);
		}
	}
	
	public function ajax_delete_img() {
		//ajax删除封面图片
		$filename = $_POST['imagename'];
		if(stristr($filename, "http://")) {
			$filename = substr($filename, strrpos($filename,"/")+1, strlen($filename));
		}
		$pic_path = dirname(dirname(__FILE__));
		$pic_path = $pic_path."/data/files/news/". $filename;
		if(file_exists($pic_path)){
			if(!empty($filename)){
				unlink($pic_path);
				echo '1';
			}else{
				echo '删除失败.';
			}
		}
	}

	/**
	 * 根据模板文件生成静态文件
	 * $target_html_file 目标文件
	 * $data 数据
	 */
	function createNewsHtml($target_html_file, $data) {
		//判断上传的图文是否添加了原文链接
		if(empty($data['news_href'])) {
			//模板文件
			$tpl_file = dirname(dirname(__FILE__))."/admin/tpl/content.tpl";
			//echo $tpl_file;
			$t_file = fopen($tpl_file, "r");
			$target_file = fopen(dirname(dirname(__FILE__))."/admin/news/".$target_html_file, "w");
			while (!feof($t_file)) {
				$line_file = fgets($t_file);
				if(stristr($line_file,"<{title}>")) {
					$line_file = str_replace("<{title}>", $data['news_title'], $line_file);
				}
				if(stristr($line_file,"<{date}>")) {
					$line_file = str_replace("<{date}>", date("Y-m-d H:i:s",$data['news_time']), $line_file);
				}
				if(stristr($line_file,"<{content}>")) {
					$news_content = str_replace("\\", "",$data['news_content']);
					$line_file = str_replace("<{content}>", $news_content, $line_file);
					
				}
				if(stristr($line_file,"<{wx_number}>")) {
					$line_file = str_replace("<{wx_number}>", "东辉", $line_file);
				}
				fwrite($target_file, $line_file);
			}
			fclose($t_file);
			fclose($target_file);
		}
	}
	
	/**
	 * 缩略图主函数
	 * @param string $src 图片路径
	 * @param int $w 缩略图宽度
	 * @param int $h 缩略图高度
	 * @return mixed 返回缩略图路径
	 * **/
	
	function resize($src,$w,$h)
	{
		$temp=pathinfo($src);
		$name=$temp["basename"];//文件名
		$dir=$temp["dirname"];//文件所在的文件夹
		$extension=$temp["extension"];//文件扩展名
		$savepath="{$dir}/{$name}";//缩略图保存路径,新的文件名为*.thumb.jpg
	
		//获取图片的基本信息
		$info=getImageInfo($src);
		$width=$info[0];//获取图片宽度
		$height=$info[1];//获取图片高度
		$per1=round($width/$height,2);//计算原图长宽比
		$per2=round($w/$h,2);//计算缩略图长宽比
	
		//计算缩放比例
		if($per1>$per2||$per1==$per2)
		{
			//原图长宽比大于或者等于缩略图长宽比，则按照宽度优先
			$per=$w/$width;
		}
		if($per1<$per2)
		{
			//原图长宽比小于缩略图长宽比，则按照高度优先
			$per=$h/$height;
		}
		$temp_w=intval($width*$per);//计算原图缩放后的宽度
		$temp_h=intval($height*$per);//计算原图缩放后的高度
		$temp_img=imagecreatetruecolor($temp_w,$temp_h);//创建画布
		$im=create($src);
		imagecopyresampled($temp_img,$im,0,0,0,0,$temp_w,$temp_h,$width,$height);
		if($per1>$per2)
		{
			imagejpeg($temp_img,$savepath, 100);
			imagedestroy($im);
			return addBg($savepath,$w,$h,"w");
			//宽度优先，在缩放之后高度不足的情况下补上背景
		}
		if($per1==$per2)
		{
			imagejpeg($temp_img,$savepath, 100);
			imagedestroy($im);
			return $savepath;
			//等比缩放
		}
		if($per1<$per2)
		{
			imagejpeg($temp_img,$savepath, 100);
			imagedestroy($im);
			return addBg($savepath,$w,$h,"h");
			//高度优先，在缩放之后宽度不足的情况下补上背景
		}
	}
	
	function getImageInfo($src)
	{
		return getimagesize($src);
	}
	/**
	 * 创建图片，返回资源类型
	 * @param string $src 图片路径
	 * @return resource $im 返回资源类型
	 * **/
	function create($src)
	{
		$info=getImageInfo($src);
		switch ($info[2])
		{
			case 1:
				$im=imagecreatefromgif($src);
				break;
			case 2:
				$im=imagecreatefromjpeg($src);
				break;
			case 3:
				$im=imagecreatefrompng($src);
				break;
		}
		return $im;
	}
	
	/**
	 * 添加背景
	 * @param string $src 图片路径
	 * @param int $w 背景图像宽度
	 * @param int $h 背景图像高度
	 * @param String $first 决定图像最终位置的，w 宽度优先 h 高度优先 wh:等比
	 * @return 返回加上背景的图片
	 * **/
	function addBg($src,$w,$h,$fisrt="w")
	{
		$bg=imagecreatetruecolor($w,$h);
		$white = imagecolorallocate($bg,255,255,255);
		imagefill($bg,0,0,$white);//填充背景
	
		//获取目标图片信息
		$info=getImageInfo($src);
		$width=$info[0];//目标图片宽度
		$height=$info[1];//目标图片高度
		$img=create($src);
		if($fisrt=="wh")
		{
			//等比缩放
			return $src;
		}
		else
		{
			if($fisrt=="w")
			{
				$x=0;
				$y=($h-$height)/2;//垂直居中
			}
			if($fisrt=="h")
			{
				$x=($w-$width)/2;//水平居中
				$y=0;
			}
			imagecopymerge($bg,$img,$x,$y,0,0,$width,$height,100);
			imagejpeg($bg,$src,100);
			imagedestroy($bg);
			imagedestroy($img);
			return $src;
		}
	
	}
}